﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;

namespace Assignment5
{
    public class MyDbContext : DbContext
    {
        public DbSet<Order> Orders { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Goods> Goods { get; set; }

    
        public int GetNextGoodId()
        {
            return Goods.Any() ? Goods.Max(g => g.GoodId) + 1 : 1;
        }

        private int GetNextCustomerId()
        {
            return Customers.Any() ? Customers.Max(c => c.CustomerId) + 1 : 1;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var connectionString = Configuration.GetConnectionString("OrderDatabase");
            optionsBuilder.UseSqlServer(connectionString);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 在此处使用 Fluent API 配置实体和关系
            // 例如：
            // modelBuilder.Entity<Goods>().HasKey(g => g.GoodId);
            // modelBuilder.Entity<Order>().HasOne(o => o.Customer).WithMany(c => c.Orders);
        }
    }

    // 静态类，用于配置应用程序
    public static class Configuration
    {
        public static IConfiguration Root { get; } = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        public static string GetConnectionString(string name)
        {
            return Root.GetConnectionString(name);
        }
    }
}